﻿using System.Collections.Generic;
using UnityEngine;

public enum MouseIcon
{
    Null,
    Normal,
    Click,
    Attack,
    LockNormal,
    LockAlly,
    LockEnemy
}
public class CursorManager:MonoSingleton<CursorManager>
{
    private Dictionary< string ,Texture2D  > mouseIconDic;
    private List<string> igeoreOffsetLis;//用于存储需要忽略光标热点的偏移的图片名称
    /// <summary>
    /// 光标焦点
    /// </summary>
    private Vector2 hopspot; 
    private MouseIcon currentIcon = MouseIcon.Null;

    protected override void Awake()
    {
        base.Awake();
        InitMouseTexture();
        SetMouseIcon(MouseIcon.Normal);
    }
    void InitMouseTexture()
    {
        hopspot = Vector2.one;
        mouseIconDic = new Dictionary<string, Texture2D>();
        igeoreOffsetLis = new List<string>();
        Texture2D[] NormalSprites = Resources.LoadAll<Texture2D>("MouseSprites/Icons") as Texture2D[];
        Texture2D[] NoOffsetSprites = Resources.LoadAll<Texture2D>("MouseSprites/IconsNoOffset") as Texture2D[];
        for (int i = 0; i < NormalSprites.Length ; i++)
        {
            mouseIconDic.Add(NormalSprites[i].name, NormalSprites[i]);
        }

        for (int i = 0; i < NoOffsetSprites.Length; i++)
        {
            mouseIconDic.Add(NoOffsetSprites[i].name, NoOffsetSprites[i]);
            igeoreOffsetLis.Add(NoOffsetSprites[i].name);
        }
    }

    public void SetMouseIcon(MouseIcon icon)
    {//这里优化性能的操作,因为考虑到角色技能开启协程后,while循环在break前光标会无限的被调用这个方法这方法
        if (currentIcon == icon) return;
        currentIcon = icon;
        Texture2D mouseIcon;
        mouseIconDic.TryGetValue(icon.ToString(), out mouseIcon);
        if (mouseIcon != null)
        {
            float HopspotOffset = 1;
            HopspotOffset = CalculateHopspotOffset(mouseIcon);
            Cursor.SetCursor(mouseIcon,hopspot*HopspotOffset, CursorMode.Auto);
        }
        else
        {
            Debug.LogError( "没有找到对应的图标,请查看字典与枚举是否一一对应");
        }
    }
    /// <summary>
    /// 计算光标的焦点偏移,不同的图形光标焦点偏移不一样
    /// </summary>
    float CalculateHopspotOffset(Texture2D texture)
    {
        bool ignore = false;
        for (int i = 0; i < igeoreOffsetLis .Count; i++)
        {//表示忽略光标热点偏移
            if (texture.name == igeoreOffsetLis[i])
            {
                ignore = true;
                break;
            }
        }
        if (ignore) return 1;
        else
        {//因为选择的图标都是正方形的所以直接/2就定位到了中间
            return  texture.height / 2;
        }
    }
}